package com.labofjet.system.service.impl;

import com.github.pagehelper.PageInfo;
import com.labofjet.common.dto.ContextDto;
import com.labofjet.common.util.JSONUtils;
import com.labofjet.system.annotation.RedisCacheEvicat;
import com.labofjet.system.constant.CRedisCacheConstant;
import com.labofjet.system.dto.SysMenuDto;
import com.labofjet.system.dto.SysMenuExample;
import com.labofjet.system.mapper.SysMenuMapper;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class SysMenuServiceImpl extends CrudBaseServiceImpl<SysMenuDto> {
	@Resource
	private SysMenuMapper sysMenuMapper;

	@Override
	@Cacheable(value = CRedisCacheConstant.MENU_PAGE_PREFIX, key = CRedisCacheConstant.CACHE_PAGE)
	public PageInfo<SysMenuDto> list(ContextDto result) {
		Map<String, Object> map = super.prepare(result);
		List<SysMenuDto> sysMenuDtos = sysMenuMapper.selectList(map);
		return new PageInfo<>(sysMenuDtos);
	}

	@Override
	@Cacheable(value = CRedisCacheConstant.MENU_ID_PREFIX, key = CRedisCacheConstant.CACHE_ID)
	public SysMenuDto load(ContextDto result) {
		Map<String, Object> map = super.getRequestParamsMap(result);
		Integer id = (Integer) map.get("id");
		if (null != id) {
			return sysMenuMapper.selectList(map).get(0);
		}
		return null;
	}

	@Override
	@Transactional
	@Caching(evict = {
			@CacheEvict(value = CRedisCacheConstant.MENU_ID_PREFIX, key = CRedisCacheConstant.CACHE_EVICT_ID)
	})
	@RedisCacheEvicat(evict = @CacheEvict(value = CRedisCacheConstant.MENU_PAGE_PREFIX, allEntries = true))
	public SysMenuDto save(ContextDto result) {
		SysMenuDto dto = JSONUtils.getRequestData(result, SysMenuDto.class);
		if (dto.getId() != null) {
			sysMenuMapper.updateByPrimaryKey(dto);
		} else {
			sysMenuMapper.insertSelective(dto);
		}
		return dto;
	}

	@Override
	@Transactional
	@RedisCacheEvicat(evict = {@CacheEvict(value = CRedisCacheConstant.MENU_PAGE_PREFIX, allEntries = true),
		@CacheEvict(value = CRedisCacheConstant.MENU_ID_PREFIX)})
	public int delete(ContextDto result) {
		List<Integer> ids = JSONUtils.getRequestData(result, List.class);
		SysMenuExample example = new SysMenuExample();
		example.createCriteria().andIdIn(ids);
		int i = sysMenuMapper.deleteByExample(example);
		return i;
	}

	/**
	 * 首页菜单查询,要过滤权限
	 *
	 * @param result
	 * @return
	 */
	public PageInfo<SysMenuDto> menuList(ContextDto result) {
		Map<String, Object> map = super.prepare(result);
		List<SysMenuDto> sysMenuDtos = sysMenuMapper.selectMenuList(map);
		return new PageInfo<>(sysMenuDtos);
	}
}
